/**
 * 切片上传
 *
 */
const PATH = require("path");
const FS = require("fs");
const mkDir = require("./ApiMkDir");
const formidable = require("formidable");
const form = new formidable.IncomingForm();
module.exports = function (req, res, config) {
  return new Promise((resolve, reject) => {
    let { savePath, cachePath } = config;
    // 判断目录是否存在，不存在创建目录
    if (!FS.existsSync(savePath)) mkDir(savePath);
    if (!FS.existsSync(cachePath)) mkDir(cachePath);
    form.parse(req, (err, fields, files) => {
      // 获取分片数据
      let { index, total, md5 } = fields;
      // 临时文件路径
      let TmpFileName = cachePath + "/" + files["file"].name;
      // 存储文件路径
      let FileName = savePath + "/" + files["file"].name;
      // 当前文件传输进度管理
      let TmpFileNameMange = cachePath + "/" + files["file"].name + ".txt";
      TmpFileName = PATH.normalize(TmpFileName);
      TmpFileNameMange = PATH.normalize(TmpFileNameMange);
      FileName = PATH.normalize(FileName);
      // 是否第一次传输
      if (FS.existsSync(FileName)) FS.unlinkSync(FileName);
      if (FS.existsSync(TmpFileNameMange)) {
        let test = FS.readFileSync(TmpFileNameMange, { encoding: "utf-8" });
        if (test) {
          let { i, md5: md } = JSON.parse(test);
          if (md === md5 && Number(i) > Number(index)) {
            resolve(i);
            return;
          }
        }
      }
      // 获取上传的文件buffer
      let buffer = FS.readFileSync(files["file"].path);
      // 写入临时文件
      if (FS.appendFileSync(TmpFileName, buffer)) reject();
      // 传输完成，移动到保存目录
      // 写入保存文件
      FS.writeFileSync(
        TmpFileNameMange,
        JSON.stringify({ i: index, total, md5 })
      );
      if (index === total) {
        FS.renameSync(TmpFileName, FileName);
        FS.unlinkSync(TmpFileNameMange);
        resolve();
        return;
      }
      resolve(index);
    });
  });
};
